import { Chapter, ChapterArgs, ChapterGroup } from "../types/Chapter";
import { BaseRepository } from "./BaseRepository";
import { relationalStore } from "@kit.ArkData";

export class ChapterRepository extends BaseRepository {

  private resultSetToItem(resultSet: relationalStore.ResultSet): Chapter {
    const chapter: Chapter = {
      id: resultSet.getLong(0),
      plugin_id: resultSet.getLong(1),
      book_id: resultSet.getLong(2),
      name: resultSet.getString(3),
      url: resultSet.getString(4),
      content: resultSet.getString(5),
      group_name: resultSet.getString(6),
      is_read: resultSet.getLong(7) === 1,
      create_at: resultSet.getLong(8),
      update_at: resultSet.getLong(9),
    }
    return chapter
  }

  async findByBookId(id: number): Promise<Chapter[]> {
    const resultSet = await this.db.querySql("select * from chapter where book_id = ?", [id])
    const result: Chapter[] = []
    const firstRow = resultSet.goToFirstRow();
    if (firstRow) {
      do {
        const chapter: Chapter = this.resultSetToItem(resultSet)
        result.push(chapter)
      } while (resultSet.goToNextRow())
    }
    return result
  }

  async create(chapter: ChapterArgs): Promise<number> {
    chapter.create_at = new Date().getTime()
    chapter.update_at = 0
    return await this.db.insert("chapter", chapter)
  }

  async bulkCreate(chapters: ChapterArgs[]) {
    for (const chapter of chapters) {
      chapter.update_at = 0
      chapter.create_at = new Date().getTime()
    }
    await this.db.batchInsert("chapter", chapters)
  }


  async update(id: number, chapter: ChapterArgs): Promise<number> {
    chapter.update_at = new Date().getTime()
    let predicates = new relationalStore.RdbPredicates("chapter");
    predicates.equalTo("id", id);
    return await this.db.update(chapter, predicates)
  }

  async findGroupByBookId(id: number): Promise<ChapterGroup[]> {
    const existingChapters = await this.findByBookId(id)
    if (existingChapters && existingChapters.length > 0) {
      // 如果数据库中有数据，按分组返回
      const groups = new Map<string, Chapter[]>()
      for (const chapter of existingChapters) {
        if (!groups.has(chapter.group_name)) {
          groups.set(chapter.group_name, [])
        }
        groups.get(chapter.group_name)!.push(chapter)
      }
      return Array.from(groups.entries()).map(v => {
        return {
          name: v[0],
          data: v[1]
        } as ChapterGroup
      })
    }
    return []
  }


}